package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class PublishListener {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    IAuditService auditService;

    @PostConstruct//实例化后自动执行该方法
    public void init () {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //开启redission队列监听器
                RBlockingQueue<String> queue = redissonClient.getBlockingQueue("article-publish");
                //启动时发送一条初始化消息，建立通道
                //创建延迟队列
                RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(queue);
                //发送消息
                delayedQueue.offer("init",1, TimeUnit.SECONDS);
                try {
                    while (true) {
                        String poll = queue.poll(30, TimeUnit.SECONDS);
                        if (!StringUtils.isEmpty(poll) && !poll.equals("init")) {
                            System.out.println("接收到的消息" + poll + ",时间为" + new Date());
                            //转换成文章对象
                            WmNews wmNews = JSON.parseObject(poll, WmNews.class);
                            //重新进入审核流程
                            auditService.aduit(wmNews);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
